/*
 *
 *  * Copyright (c) 2016. For Intelligent Group.
 *
 */

package com.intelligent.mts.client.utils;

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Created by Peter on 2016/7/13.
 */
public class ApplicationBeanUtils implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext = null;

    private static Logger logger = LoggerFactory.getLogger(ApplicationBeanUtils.class);

    /**
     * Get ApplicationContext.
     */
    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }

    /**
     * Get bean from applicationContext.
     */
    public static <T> T getBean(String name) {
        assertContextInjected();
        return (T) applicationContext.getBean(name);
    }

    /**
     * Get bean from applicationContext.
     */
    public static <T> T getBean(Class<T> requiredType) {
        assertContextInjected();
        return applicationContext.getBean(requiredType);
    }

    /**
     * Clear ApplicationContext in SpringContextHolder to Null.
     */
    public static void clearHolder() {
        logger.debug("Clear the ApplicationContext in SpringContextHolder:" + applicationContext);
        applicationContext = null;
    }

    /**
     * Implement ApplicationContextAware.
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        logger.debug("Inject ApplicationContext to SpringContextHolder:{}", applicationContext);

        if (ApplicationBeanUtils.applicationContext != null) {
            logger.warn("The ApplicationContext is override which in SpringContextHolder, ApplicationContext:"
                    + ApplicationBeanUtils.applicationContext);
        }

        ApplicationBeanUtils.applicationContext = applicationContext; //NOSONAR
    }

    /**
     * Implements DisposableBean, Clean static var when closing Context.
     */
    @Override
    public void destroy() throws Exception {
        ApplicationBeanUtils.clearHolder();
    }

    /**
     * Check ApplicationContext is not null.
     */
    private static void assertContextInjected() {
        Validate.validState(applicationContext != null,
                "applicaitonContext does not be inject, please detect SpringContextHolder in the spring.xml");
    }
}
